package com.yifushidai.aspect;

import com.alibaba.fastjson.JSON;
import com.yifushidai.annotation.UserHolder;
import com.yifushidai.entity.OptDeviceLog;
import com.yifushidai.mapper.OptDeviceLogMapper;
import com.yifushidai.utils.IpUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class WebLogAspect {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OptDeviceLogMapper optDeviceLogMapper;

    @Pointcut("execution(* com.yifushidai.api..*(..))")
    public void declareJoinPointExpression() {
    }


    @Before("declareJoinPointExpression()")
    public void doBefore(JoinPoint joinPoint) {

//        logger.info("WebLogAspect.doBefore()");

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求内容
//        logger.info("URL : " + request.getRequestURL().toString());
//        logger.info("HTTP_METHOD : " + request.getMethod());
//        logger.info("IP : " + request.getRemoteAddr());
//        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
//        logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

        //获取所有参数方法一：
//        Enumeration<String> enu = request.getParameterNames();
//        while (enu.hasMoreElements()) {
//            String paraName = enu.nextElement();
//            System.out.println(paraName + ": " + request.getParameter(paraName));
//        }
        //获取所有参数方法二：
        logger.warn("<<< 请求({})：{} 参数：{}", IpUtil.getIpAddress(request), request.getRequestURL(), JSON.toJSONString(request.getParameterMap()));

        String mobile = (UserHolder.get() == null ? "" : UserHolder.get().getMobile());
        optDeviceLogMapper.insertSelective(
                OptDeviceLog.builder()
                        .addressSocket(IpUtil.getIpAddress(request))
                        .mobile(mobile)
                        .logType("APP")
                        .alias(request.getRequestURI())
                        .optDesc(JSON.toJSONString(request.getParameterMap()))
                        .build());
    }

    @AfterReturning(pointcut = "declareJoinPointExpression()", returning = "result")
    public void doAfterReturning(JoinPoint joinPoint, Object result) {

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 处理完请求，返回内容
        logger.info(">>> 响应({})：{}", IpUtil.getIpAddress(request), JSON.toJSONString(result));

//        logger.info("WebLogAspect.doAfterReturning()");
    }
}